package cn.rongdao.jrkabao.ui.cashadvance.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.TextView;

import com.baidu.ocr.ui.camera.CameraActivity;
import com.chanven.lib.cptr.recyclerview.RecyclerAdapterWithHF;
import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.inputmethod.FRView;
import com.mifengkong.frtools.ui.adapter.recyclerview.FRBaseRecyclerAdapter;
import com.mifengkong.frtools.util.FRString;
import com.mifengkong.frtools.util.FRToast;
import com.mifengkong.frtools.util.PictureUtil;
import com.mifengkong.frwidget.dialog.FRDialog;
import com.mifengkong.frwidget.dialog.FRDialogClickListener;
import com.mifengkong.frwidget.recyclerview.PtrRecyclerViewUIComponent;
import com.mifengkong.frwidget.refersh.OnPullToRefreshListener;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.base.BaseViewPagerFragment;
import cn.rongdao.jrkabao.bean.cashadvance.CreditAndDepositCardBean;
import cn.rongdao.jrkabao.bean.takephoto.BankCardOCRBean;
import cn.rongdao.jrkabao.model.cashadvance.DeleteCreditCardModel;
import cn.rongdao.jrkabao.model.cashadvance.SetDefaultCreditCardModel;
import cn.rongdao.jrkabao.model.takephoto.BankCardOCRModel;
import cn.rongdao.jrkabao.ui.cashadvance.adapter.CreditAndDepositCardAdapter;
import cn.rongdao.jrkabao.ui.cashadvance.adapter.CreditAndDepositViewHolder;
import cn.rongdao.jrkabao.ui.cashadvance.addcard.BaseAddCreditCardOrDepositCardActivity;
import cn.rongdao.jrkabao.ui.cashadvance.event.ChangeCreditCardEvent;
import cn.rongdao.jrkabao.ui.cashadvance.event.ChangeDepositCardEvent;
import cn.rongdao.jrkabao.ui.cashadvance.uicomponent.CashEmptyUIComponent;
import cn.rongdao.jrkabao.ui.deposit.event.DepositAddCardEvent;
import cn.rongdao.jrkabao.util.CommonUtil;
import cn.rongdao.jrkabao.util.permission.GoToPermissionSetting;

import static cn.rongdao.jrkabao.ui.cashadvance.addcard.BaseAddCreditCardOrDepositCardActivity.REQUEST_CODE_BANKCARD;

/**
 * Created by jack on 2017/6/2
 */

public abstract class BaseCardFragment extends BaseViewPagerFragment implements FRBaseRecyclerAdapter.OnItemClickListener<CreditAndDepositViewHolder> {

    @BindView(R.id.fc_ptr_framelayout)
    PtrRecyclerViewUIComponent ptrRecyclerViewUIComponent;
    @BindView(R.id.fc_empty_view)
    CashEmptyUIComponent emptyView;

    TextView tvAddCard;
    CreditAndDepositCardAdapter creditAndDepositCardAdapter;

    protected String id;
    private boolean isHavePermission;

    @Override
    protected int layoutRes() {
        return R.layout.fragment_credit;
    }

    private void checkPermission() {
        AndPermission.with(this)
                .requestCode(100)
                .permission(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        isHavePermission = true;
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        isHavePermission = false;
                    }
                }).start();
    }

    private boolean lackPermission() {
        if (!isHavePermission) {
            GoToPermissionSetting.showSnackBar(getActivity(), findView(android.R.id.content));
            return true;
        }
        return false;
    }

    @Override
    protected void onViewReallyCreated(View view) {
        super.onViewReallyCreated(view);
        EventBus.getDefault().register(this);
        checkPermission();
        ptrRecyclerViewUIComponent.setBackground(R.color.layout_bg);

        creditAndDepositCardAdapter = new CreditAndDepositCardAdapter(getContext(), this);
        RecyclerAdapterWithHF mAdapter = new RecyclerAdapterWithHF(creditAndDepositCardAdapter);
        View viewFooter = FRView.inflateLayout(getContext(), R.layout.layout_add_new_credit, null);
        if (viewFooter != null) {
            tvAddCard = viewFooter.findViewById(R.id.lanc_tv_add_card);
            mAdapter.addFooter(viewFooter);
        }
        ptrRecyclerViewUIComponent.setLayoutManager(new LinearLayoutManager(getContext()));
        ptrRecyclerViewUIComponent.setAdapter(mAdapter);
        initListener();
    }

    @Override
    protected void lazyLoad() {
        super.lazyLoad();
        ptrRecyclerViewUIComponent.delayRefresh();
    }

    protected void initListener() {
        ptrRecyclerViewUIComponent.setOnPullToRefreshListener(new OnPullToRefreshListener() {
            @Override
            public void onPullToRefresh() {
                requestData();
            }
        });
    }

    protected abstract void requestData();

    protected void runUiThreadSetEmptyVisible(boolean isCredit) {
        if (isCredit) {
            emptyView.initCridetCardEmpty();
        } else {
            emptyView.initDepositCardEmpty();
        }
        if (tvAddCard != null) {
            tvAddCard.setVisibility(View.GONE);
        }
        ptrRecyclerViewUIComponent.setVisibility(View.GONE);
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    protected void showDeleteDialog(final int position, final boolean isCredit) {
        new FRDialog.MDBuilder(getActivity())
                .setMessage("确认删除绑定的银行卡吗？")
                .setNegativeContentAndListener("取消", null)
                .setNegativeTextColor(ContextCompat.getColor(getContext(), R.color.c333333))
                .setPositiveTextColor(ContextCompat.getColor(getContext(), R.color.colorPrimary))
                .setPositiveContentAndListener("确认",new FRDialogClickListener() {
                    @Override
                    public boolean onDialogClick(View view) {
                        deleteCreditCard(position, isCredit);
                        return true;
                    }
                })
                .show();
    }

    protected void settingDefaultCard(int position, boolean isCredit) {
        if (isCredit) {
            SetDefaultCreditCardModel.getInstance().executeCreditCard(creditAndDepositCardAdapter.getDataList().get(position).getId()
                    , new FRBaseObserver<String>(this, "正在设置主卡，请稍候...") {
                        @Override
                        protected void onBaseNext(String data) {
                            FRToast.showToastSafe("设置主卡成功");
                            EventBus.getDefault().post(new ChangeCreditCardEvent());
                        }
                    });
        } else {
            SetDefaultCreditCardModel.getInstance().executeDepositCard(creditAndDepositCardAdapter.getDataList().get(position).getId()
                    , new FRBaseObserver<String>(this, "正在设置主卡，请稍候...") {
                        @Override
                        protected void onBaseNext(String data) {
                            FRToast.showToastSafe("设置主卡成功");
                            EventBus.getDefault().post(new ChangeDepositCardEvent());
                        }
                    });
        }
    }

    private void deleteCreditCard(final int position, boolean isCredit) {
        if (isCredit) {
            DeleteCreditCardModel.getInstance().executeCreditCard(creditAndDepositCardAdapter.getDataList().get(position).getId()
                    , new FRBaseObserver<String>(this, "正在删除信用卡，请稍候...") {
                        @Override
                        protected void onBaseNext(String data) {
                            FRToast.showToastSafe("删除成功");
                            EventBus.getDefault().post(new ChangeCreditCardEvent());
                            creditAndDepositCardAdapter.removeItem(position);
                            if (creditAndDepositCardAdapter.getDataList().size() < 1) {
                                runUiThreadSetEmptyVisible(true);
                            }
                        }
                    });
        } else {
            DeleteCreditCardModel.getInstance().executeDepositCard(creditAndDepositCardAdapter.getDataList().get(position).getId()
                    , new FRBaseObserver<String>(this, "正在删除储蓄卡，请稍候...") {
                        @Override
                        protected void onBaseNext(String data) {
                            FRToast.showToastSafe("删除成功");
                            EventBus.getDefault().post(new ChangeDepositCardEvent());
                            creditAndDepositCardAdapter.removeItem(position);
                            if (creditAndDepositCardAdapter.getDataList().size() < 1) {
                                runUiThreadSetEmptyVisible(true);
                            }
                        }
                    });
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeCreditCardEvent(ChangeCreditCardEvent changeCreditCardEvent) {
        requestData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeDepositCardEvent(ChangeDepositCardEvent changeDepositCardEvent) {
        requestData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void depositAddCardEventEvent(DepositAddCardEvent depositAddCardEvent) {
        requestData();
    }

    @Override
    public void onItemClick(CreditAndDepositViewHolder creditAndDepositViewHolder, int position) {
        CreditAndDepositCardBean creditAndDepositCardBean = creditAndDepositCardAdapter.getDataList().get(position);
        id = creditAndDepositCardBean.getId();
        if (!CommonUtil.isStatusSuccess(creditAndDepositCardBean.getStatus()) && !lackPermission()) {
            Intent intent = new Intent(getContext(), CameraActivity.class);
            intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH, CommonUtil.getSaveFile(getContext()).getAbsolutePath());
            intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_BANK_CARD);
            startActivityForResult(intent, REQUEST_CODE_BANKCARD);
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 识别成功回调，银行卡识别
        if (requestCode == BaseAddCreditCardOrDepositCardActivity.REQUEST_CODE_BANKCARD && resultCode == Activity.RESULT_OK) {
            String imagePath = CommonUtil.getSaveFile(getContext()).getAbsolutePath();
            if (!FRString.isEmpty(imagePath)) {
                bankCardOCR(PictureUtil.bitmapToString(imagePath));
            }
        }
    }

    private void bankCardOCR(String base64) {
        BankCardOCRModel.getInstance()
                .addParam("type", isCredit() ? "2" : "1")
                .addParam("id", FRString.valueOf(id))
                .addParam("obverse_pic", base64)
                .execute(new FRBaseObserver<BankCardOCRBean>(this, "正在识别，请稍候...") {
                    @Override
                    protected void onBaseNext(BankCardOCRBean data) {
                        FRToast.showToastSafe("补全成功");
                        requestData();
                    }
                });
    }

    protected boolean isCredit() {
        return false;
    }
}